import { createRouter, createWebHistory } from 'vue-router'
import Order from '@/views/Order.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Index.vue')
  },
  {
    path: '/index',
    name: 'Index',
    component: () => import('../views/Index.vue')
  },
  {
    path: '/businessList',
    name: 'BusinessList',
    component: () => import('../views/BusinessList.vue')
  },
  {
    path: '/businessInfo',
    name: 'BusinessInfo',
    component: () => import('../views/BusinessInfo.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/orders',
    name: 'Orders',
    component: () => import('../views/Order.vue'),
    meta: {
      keepAlive: true
    }
  },
  {
    path: '/userAddress',
    name: 'UserAddress',
    component: () => import('../views/UserAddress.vue')
  },
  {
    path: '/payment',
    name: 'Payment',
    component: () => import('../views/Payment.vue')
  },
  {
    path: '/orderList',
    name: 'OrderList',
    component: () => import('../views/OrderList.vue')
  },
  {
    path: '/addUserAddress',
    name: 'AddUserAddress',
    component: () => import('../views/AddUserAddress.vue')
  },
  {
    path: '/editUserAddress',
    name: 'EditUserAddress',
    component: () => import('../views/EditUserAddress.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/userInfo',
    name: 'UserInfo',
    component: () => import('../views/UserInfo.vue')
  },
  {
    path: '/order',
    name: 'Order',
    component: Order
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  // 需要登录才能访问的路由
  const authRoutes = ['/orderList', '/userInfo', '/order', '/payment', '/userAddress']
  
  // 获取用户信息
  const user = sessionStorage.getItem('user')
  
  // 如果是需要登录的路由，且用户未登录
  if (authRoutes.includes(to.path) && !user) {
    console.log('用户未登录，重定向到登录页面')
    next({
      path: '/login',
      query: { redirect: to.fullPath }  // 保存原目标路径
    })
  } else {
    next()
  }
})

export default router